package model

import (
	"database/sql"
	"github.com/jmoiron/sqlx"
	"strconv"
	"time"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/pkg/e"
)

type UserAmountDb struct {
	Uid         int64  `db:"uid" json:"uid"`
	PayPassword string `db:"pay_password" json:"pay_password"`
	Salt        string `db:"salt" json:"salt"`
	Status      int64  `db:"status" json:"status"`
	CreateTime  int64  `db:"create_time" json:"create_time"`
	UpdateTime  int64  `db:"update_time" json:"update_time"`
}

/*
 * @ Author: hupfei
 * @ Description: 初始化user_amount
 **/
func InitUserAmount(uid int64) (err error) {
	_, err = config.C.DB.DB.Exec("INSERT INTO user_amount (uid,create_time,update_time) VALUES (?,UNIX_TIMESTAMP(NOW()),UNIX_TIMESTAMP(NOW()))", uid)
	if err != nil {
		e.Log("err", "初始化user_amount失败:", err.Error())
	}
	return
}

//添加的转账地址是否存在
func TransferAddressExistByaddress(uid int64, address string) (ok bool) {
	var count sql.NullInt64
	err := sqlx.Get(config.C.DB.DB, &count, "SELECT COUNT(*) FROM wallet_address_list WHERE address = ? AND uid = ?", address, uid)
	if err != nil {
		e.Log("err", "TransferAddressExistByaddress 失败:", err.Error())
	}
	return count.Int64 > 0
}

func TransferAddressExistById(id int64) (ok bool) {
	var count sql.NullInt64
	err := sqlx.Get(config.C.DB.DB, &count, "SELECT COUNT(*) FROM wallet_address_list WHERE id = ?", id)
	if err != nil {
		e.Log("err", "TransferAddressExistById 失败:", err.Error())
	}
	return count.Int64 > 0
}

//添加转账地址
func InsertTransferAddress(uid int64, name, address string) (id int64, err error) {
	result, err := config.C.DB.DB.Exec(`INSERT INTO wallet_address_list(uid, address, mark, create_time) VALUES (?, ?, ?, ?)`, uid, address, name, time.Now().Unix())
	if err != nil {
		e.Log("err", "InsertTransferAddress 失败", uid, name, err.Error())
		return
	}
	id, err = result.LastInsertId()
	if err != nil {
		e.Log("info", err)
		return
	}
	return id, err
}

type TransferAddress struct {
	Id         int64  `json:"id,omitempty" db:"id"`
	Name       string `json:"name,omitempty" db:"name"`
	Address    string `json:"address,omitempty" db:"address"`
	CreateTime string `json:"createTime,omitempty" db:"create_time"`
}

//查询最后一次的转账地址
func SearchLastTransferAddress(uid int64) (info TransferAddress, err error) {
	err = sqlx.Get(config.C.DB.DB, &info, "SELECT IFNULL(address.id,0) AS id,IFNULL(address.mark,'') AS name, log.to AS address, "+
		"FROM_UNIXTIME(log.create_time,'%Y/%m/%d %H:%i') AS create_time "+
		"FROM cvn_log AS log LEFT JOIN wallet_address_list address ON log.to=address.address AND log.uid=address.uid "+
		"WHERE log.uid=? AND (source = 3 OR source = 16) ORDER BY log.id DESC LIMIT 1", uid)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		e.Log("err", "SearchLastTransferAddress 失败:", uid, err.Error())
	}
	return
}

//转账地址列表
func SearchTransferAddressList(uid int64, key string, page, per int) (info []TransferAddress, err error) {
	start := (page - 1) * per
	var sqlStr string
	if len(key) > 0 {
		sqlStr = "SELECT id, address, mark AS name, FROM_UNIXTIME(create_time, '%Y/%m/%d %H:%i') AS create_time " +
			"FROM wallet_address_list WHERE uid = " + strconv.FormatInt(uid, 10) + " AND mark LIKE '%" + key + "%' " +
			"ORDER BY id DESC LIMIT " + strconv.Itoa(start) + ", " + strconv.Itoa(per)
	} else {
		sqlStr = "SELECT id, address, mark AS name, FROM_UNIXTIME(create_time, '%Y/%m/%d %H:%i') AS create_time " +
			"FROM wallet_address_list WHERE uid = " + strconv.FormatInt(uid, 10) +
			" ORDER BY id DESC LIMIT " + strconv.Itoa(start) + ", " + strconv.Itoa(per)
	}
	err = sqlx.Select(config.C.DB.DB, &info, sqlStr)
	if err != nil {
		e.Log("err", "SearchTransferAddressList 失败", uid, err.Error())
	}
	return info, err
}

//更新转账地址
func UpdateTransferAddress(id int64, name, address string) (err error) {
	re := sqlx.MustExec(config.C.DB.DB, "UPDATE wallet_address_list SET `address` = ?, mark = ? WHERE id = ?", address, name, id)
	_, err = re.RowsAffected()
	if err != nil {
		e.Log("err", " UpdateTransferAddress 失败:", err.Error())
		return err
	}
	return
}

//删除转账地址
func DeleteTransferAddress(id int64) (err error) {
	re := sqlx.MustExec(config.C.DB.DB, "DELETE FROM wallet_address_list WHERE id = ?", id)
	_, err = re.RowsAffected()
	if err != nil {
		e.Log("err", " DeleteTransferAddress 失败:", err.Error())
		return err
	}
	return
}

//获取账户信息
//Auth: TXG
func GetUserAmount(uid int64) (qi UserAmountDb, err error) {
	err = sqlx.Get(config.C.DB.DB, &qi, "SELECT uid,pay_password,salt,status,create_time,update_time FROM user_amount WHERE uid = ?", uid)
	if err != nil {
		e.Log("err", err)
	}
	return qi, err
}
